package com.dao;
import java.sql.*;

public class wordDao {
	private static final String USER = "csc";
	private static final String PASSWORD = "Csc030414";
	private static final String URL = "jdbc:mysql://gz-cynosdbmysql-grp-qkbjy1br.sql.tencentcdb.com:27212/vst";
	private static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
	private static final String tableName = "coca20000";
	private static Connection conn;
	public static Connection getConnection() {
		if (conn == null) {
			try {
				Class.forName(JDBC_DRIVER);
				conn = DriverManager.getConnection(URL, USER, PASSWORD);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return conn;
	}
	
	public static Word getObjectbyRank(int rank) {
		try {
			PreparedStatement pstmt = wordDao.getConnection().prepareStatement("select `Rank`, WORD from "+tableName+" where `Rank` = ?");
			pstmt.setInt(1, rank);
			ResultSet rs = pstmt.executeQuery();
			if (rs.next()) {
				Word w = new Word(rs.getInt(1),rs.getString(2));
				return w;
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}
	public static Word getObjectbyWord(String word) {
		try {
			PreparedStatement pstmt = wordDao.getConnection().prepareStatement("select `Rank`, WORD from "+tableName+" where WORD = ?");
			pstmt.setString(1, word);
			ResultSet rs = pstmt.executeQuery();
			if (rs.next()) {
				Word w = new Word(rs.getInt(1),rs.getString(2));
				return w;
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}
	
	public static void main(String[] args) {
		Word w1 = wordDao.getObjectbyRank(20200);
		
		Word w2 = wordDao.getObjectbyWord("a");
		
		System.out.println("w1 rank:"+w1.getRank()+" w1 word:"+w1.getWord());
		System.out.println("w2 rank:"+w2.getRank()+" w2 word:"+w2.getWord());

	}
}

